package com.learning.concurrent.basic.designpattern.masterworker;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * description:
 *
 * @author minghuiZhang
 * @date created in  15:01 2018/5/15
 * modified by
 */
@Slf4j
@Data
public class Master {
	/**
	 * 用于承载任务
	 */
	private ConcurrentLinkedQueue<Task> workerQueue = new ConcurrentLinkedQueue<>();
	/**
	 * 用于承载所有的worker线程
	 */
	private HashMap<String,Thread> workers = new HashMap<>();
	/**
	 * 承载worker进程的执行结果
	 */
	private ConcurrentHashMap<String,Object> resultMap = new ConcurrentHashMap<>();

	public Master(Worker worker,int workerCount) {
		//每一个worker对象都需要有Master的引用workerQueue用于任务的获取，resultMap用于任务的提交。
		worker.setWorkerQueue(this.workerQueue);
		worker.setResultMap(this.resultMap);
		for (int i = 0; i < workerCount ; i++) {
			//key表示没一个worker的名字，value表示线程执行对象
			workers.put("子节点" + Integer.toString(i),new Thread(worker));

		}
	}

	/**
	 * description: 任务提交方法
	 * @param task 任务
	 * @author minghuiZhang
	 * @date 15:36 2018/5/15
	*/
	public void submit(Task task){
		this.workerQueue.add(task);
	}
	/**
	 * description:执行线程
	 * @author minghuiZhang
	 * @date 15:55 2018/5/15
	*/
	public void execute(){
		for (Thread thread:workers.values()) {
			thread.start();
		}
	}

	public boolean isComplete() {
		for (Thread thread:workers.values()) {
			if(thread.getState() != Thread.State.TERMINATED){
				return false;
			}
		}
		return true;
	}

	public int getResult() {
		int  result = 0;
		for (Object object : resultMap.values()) {
			log.info("value: {}",object.toString());
			result ++;
		}
		log.info("result:{}",result);
		return result;
	}
}
